// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const {
    dishId, // 菜品ID
    status, // 状态：1-上架，0-下架
  } = event;
  const { OPENID } = cloud.getWXContext();

  try {
    // 查询菜品信息
    const dishResult = await db.collection("dishes").doc(dishId).get();
    const dish = dishResult.data;

    // 查询商家信息
    const merchantResult = await db
      .collection("merchants")
      .doc(dish.merchantId)
      .get();
    const merchant = merchantResult.data;

    // 验证商家权限
    if (merchant._openid !== OPENID) {
      return {
        code: -1,
        msg: "无权限修改此菜品状态",
      };
    }

    // 更新菜品状态
    const result = await db
      .collection("dishes")
      .doc(dishId)
      .update({
        data: {
          status,
          updateTime: db.serverDate(),
        },
      });

    return {
      code: 0,
      msg: "更新成功",
      data: result,
    };
  } catch (err) {
    console.error(err);
    return {
      code: -1,
      msg: "更新失败",
      error: err,
    };
  }
};
